/**
 * 文件解析
 * @param file
 * @param type
 * @returns {Promise<unknown>}
 */
export function fileParse(file, type = 'base64') {
  return new Promise((resolve, reject) => {
    try {
      const fileReader = new FileReader()
      if (type === 'base64') {
        fileReader.readAsDataURL(file)
      } else if (type === 'buffer') {
        fileReader.readAsArrayBuffer(file)
      }
      fileReader.onload = (e) => {
        resolve(e.target.result)
      }
    } catch (err) {
      reject(err)
    }
  })
}

/**
 * 文件下载
 * @param url
 */
export function fileDownload (url) {
  const xhr = new XMLHttpRequest();
  xhr.open('post', url);
  xhr.onprogress = function (event) {
    console.log(Math.round(event.loaded) / event.total * 100 + '%');
  };
  xhr.responseType = 'arraybuffer';
  xhr.send();
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === '200') {
      // 获取响应头主要获取附件名称
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      // 获取类型和编码
      const contentType = xhr.getResponseHeader('Content-Type');
      // 构造blob对象
      const blob = new Blob([xhr.response], {
        type: contentType
      });
      const url = window.URL.createObjectURL(blob);
      // 获取文件名
      const regex = /filename=[^;]*/;
      const matchs = contentDisposition.match(regex);
      let filename = '';
      if (matchs) {
        filename = decodeURIComponent(match[0].split('=')[1]);
      } else {
        filename = Date.now() + '.doc';
      }
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  }
}
